import React, { Component } from 'react'
import {
  Form,
  Input,
  Row,
  Col,
  Checkbox,
  Button,
  Card,
  Upload,
  Icon,
  Modal,
  message,
  Tag,
  Tooltip,
  Radio
} from 'antd'
// import { uploadBook } from '../../../requests'
import './index.less'
import { bookUpload } from '../../../requests/bookDo'
const RadioGroup = Radio.Group
@Form.create({ name: 'register' })
export default class BooksUpload extends Component {
  constructor() {
    super()
    this.state = {
      confirmDirty: false,
      autoCompleteResult: [],
      previewVisible: false,
      previewImage: '',
      fileList: [],
      visible: false,
      valuePropName: 'dischencked',
      dealChecked: false,
      tag: '',
      inputVisible: false,
      inputValue: '',
      classifyValue: '',
      tagValue: '',
      iconLoading: false
    }
  }
  //classify单选框
  onChangeClassify = e => {
    this.setState({
      classifyValue: e.target.value
    })
  }
  //tag单选框
  onChangeTag = e => {
    this.setState({
      tagValue: e.target.value
    })
  }
  //   handleClose = removedTag => {
  //     const tags = this.state.tags.filter(tag => tag !== removedTag)
  //     this.setState({ tags })
  //   }

  //   showInput = () => {
  //     this.setState({ inputVisible: true }, () => this.input.focus())
  //   }

  //   handleInputChange = e => {
  //     this.setState({ inputValue: e.target.value })
  //   }

  //   handleInputConfirm = () => {
  //     const { inputValue } = this.state
  //     let { tags } = this.state
  //     if (inputValue && tags.indexOf(inputValue) === -1) {
  //       tags = [...tags, inputValue]
  //     }
  //     this.setState({
  //       tags,
  //       inputVisible: false,
  //       inputValue: ''
  //     })
  //   }

  //   saveInputRef = input => (this.input = input)
  //显示换书协议页面
  showModal = () => {
    this.setState({
      visible: true
    })
  }
  //同意换书协议
  handleOk = e => {
    console.log(e)
    this.setState({
      visible: false,
      dealChecked: true
    })
  }
  //拒绝换书协议
  handleAgreementCancel = e => {
    console.log(e)
    this.setState({
      visible: false,
      dealChecked: false
    })
  }
  //取消上传图片
  handleImgCancel = () => this.setState({ previewVisible: false })
  //图片预览
  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true
    })
  }
  //图片上传
  handleChange = ({ fileList }) => this.setState({ fileList })
  //上传按钮
  handleSubmit = e => {
    e.preventDefault()
    const userId = JSON.parse(window.sessionStorage.getItem('usermessage'))
      .userid
    this.props.form.validateFieldsAndScroll((err, values) => {
      //上传书籍
      if (!err) {
        this.setState({
          iconLoading: true
        })
        values.agreement === true
          ? // ? uploadBook({
            bookUpload({
              userId,
              ...values,
              booksimgs: this.state.fileList,
              bookstags: this.state.tags
            }).then(resp => {
              if (resp.data.data.status === 1) {
                message.success('上传成功')
                this.setState({ iconLoading: false }, () => {
                  const usermessage = JSON.parse(
                    window.sessionStorage.getItem('usermessage')
                  )
                  usermessage.mybooks = usermessage.mybooks.concat(
                    `,${resp.data.data.data.bookId}`
                  )
                  window.sessionStorage.setItem(
                    'usermessage',
                    JSON.stringify(usermessage)
                  )
                })
                this.props.history.push('/admin/mybooks')
              }
            })
          : message.error('请先阅读读书协议并同意')
      }
    })
  }

  render() {
    // const { tags, inputVisible, inputValue } = this.state
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 16,
          offset: 4
        }
      }
    }

    const { previewVisible, previewImage, fileList } = this.state
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    )
    return (
      <Card title="书籍上传" bordered={false} style={{ width: '100%' }}>
        <Form {...formItemLayout} onSubmit={this.handleSubmit}>
          <Form.Item label="书名">
            {getFieldDecorator('bookname', {
              rules: [
                {
                  required: true,
                  message: '请输入书名!'
                }
              ]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="作者">
            {getFieldDecorator('author', {
              rules: [
                {
                  required: true,
                  message: '请输入作者!'
                }
              ]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="版本号">
            {getFieldDecorator('bookversion', {
              rules: [
                {
                  required: true,
                  message: '请输入版本号!'
                }
              ]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="出版社">
            {getFieldDecorator('bookpress', {
              rules: [
                {
                  required: true,
                  message: '请输入出版社!'
                }
              ]
            })(<Input />)}
          </Form.Item>

          <Form.Item label="书籍描述">
            {getFieldDecorator('bookDescribe', {
              rules: [
                {
                  required: true,
                  message: '请简单描述本书!'
                }
              ]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="书籍图片">
            <div className="clearfix">
              <Upload
                action="//jsonplaceholder.typicode.com/posts/"
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
              >
                {fileList.length >= 5 ? null : uploadButton}
              </Upload>
              <Modal
                visible={previewVisible}
                footer={null}
                onCancel={this.handleImgCancel}
              >
                <img
                  alt="example"
                  style={{ width: '100%' }}
                  src={previewImage}
                />
              </Modal>
            </div>
          </Form.Item>
          <Form.Item label="分类">
            {getFieldDecorator('classify', {
              initialValue: [],
              rules: [
                {
                  required: true,
                  message: '请为您的书籍选择分类,以方便管理!'
                }
              ]
            })(
              <RadioGroup
                onChange={this.onChangeClassify}
                className="radiogroup"
              >
                <Radio value={'人文社科'}>人文社科</Radio>
                <Radio value={'经济管理'}>经济管理</Radio>
                <Radio value={'文学'}>文学</Radio>
                <Radio value={'生活图书'}>生活图书</Radio>
                <Radio value={'文化艺术'}>文化艺术</Radio>
                <Radio value={'科学技术'}>科学技术</Radio>
                <Radio value={'医学卫生'}>医学卫生</Radio>
                <Radio value={'文化教育'}>文化教育</Radio>
                <Radio value={'其他'}>其他</Radio>
              </RadioGroup>
            )}
          </Form.Item>
          <Form.Item label="方式">
            {getFieldDecorator('tag', {
              initialValue: [],
              rules: [
                {
                  required: true,
                  message: '请为您的书籍选择处理方式!'
                }
              ]
            })(
              <RadioGroup onChange={this.onChangeTag} className="radiogroup">
                <Radio value={'仅借阅'}>仅借阅</Radio>
                <Radio value={'仅出售'}>仅出售</Radio>
                <Radio value={'借阅+出售'}>借阅+出售</Radio>
              </RadioGroup>
            )}
          </Form.Item>
          {/* <Form.Item label="标签">
            {getFieldDecorator('`userDescribe', {
              initialValue: []
            })(
              <div>
                {tags.map((tag, index) => {
                  const isLongTag = tag.length > 5
                  const tagElem = (
                    <Tag
                      key={tag}
                      closable={true}
                      onClose={() => this.handleClose(tag)}
                    >
                      {isLongTag ? `${tag.slice(0, 5)}...` : tag}
                    </Tag>
                  )
                  return isLongTag ? (
                    <Tooltip title={tag} key={tag}>
                      {tagElem}
                    </Tooltip>
                  ) : (
                    tagElem
                  )
                })}
                {inputVisible && (
                  <Input
                    ref={this.saveInputRef}
                    type="text"
                    size="small"
                    style={{ width: 78 }}
                    value={inputValue}
                    onChange={this.handleInputChange}
                    onBlur={this.handleInputConfirm}
                    onPressEnter={this.handleInputConfirm}
                  />
                )}
                {!inputVisible && (
                  <Tag
                    onClick={this.showInput}
                    style={{ background: '#fff', borderStyle: 'dashed' }}
                  >
                    <Icon type="plus" /> New Tag
                  </Tag>
                )}
              </div>
            )}
          </Form.Item> */}
          <Form.Item {...tailFormItemLayout}>
            {getFieldDecorator('agreement', {
              valuePropName: 'checked',
              initialValue: this.state.dealChecked
            })(
              <Checkbox>
                我同意
                <a href="##" onClick={this.showModal}>
                  书籍交换协议
                </a>
              </Checkbox>
            )}
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button
              type="primary"
              htmlType="submit"
              loading={this.state.iconLoading}
            >
              上传
            </Button>
          </Form.Item>
        </Form>
        <Modal
          title="书籍交换协议"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleAgreementCancel}
          cancelText={'不同意'}
          okText={'同意'}
        >
          <p>Some contents...</p>
          <p>Some contents...</p>
          <p>Some contents...</p>
        </Modal>
      </Card>
    )
  }
}
